package org.jiucai.app.demo.listener;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.jiucai.app.demo.helper.AppHelper;
import org.jiucai.appframework.base.listener.AbstractSecureRequestListener;
import org.jiucai.appframework.base.util.ConfigUtil;


public class AppRequestListener extends AbstractSecureRequestListener {

	/**
	 * 配置项读取类
	 */
	protected static Configuration config;

	private static final Boolean appDebug;
	private static final String appTimestamp;
	private static final String appVersion;
	private static final String appJsLogEnabled;
	

	static {
		config = ConfigUtil.addConfig("config");
		
		appDebug = config.getBoolean("common.app.env.debug", false);
		appTimestamp = config.getString("common.app.env.timestamp", "20120607");

		appVersion = config.getString("common.app.env.info", "v 1.0");

		appJsLogEnabled = config.getString("common.app.env.js_log_enabled","yes");
	}

	public AppRequestListener() {
		super();
		log.info("AppRequestListener loaded config.properties.");
		log.info("AppRequestListener 加载成功...");
	}

	@Override
	public void doSecureRequest(HttpServletRequest request) {

		// debug 模式每次刷新
		if(appDebug){
			request.setAttribute("commonAppTimestamp", String.valueOf( System.currentTimeMillis()));
		}else{
			request.setAttribute("commonAppTimestamp", appTimestamp);
		}
		
		
		
		
		request.setAttribute("commonAppVersion", appVersion);
		request.setAttribute("commonAppJsLogEnabled", appJsLogEnabled);

		String appPath = null;
		String appBase = null;

		// 使用不同的IP或域名访问，会导致 上下文路径值不同，因此不能使用静态变量

		appPath = request.getContextPath();
//		String sessId = request.getSession().getId();

		// 如果应用部署的站点根目录，则 path 值为空，导致部分URL跳转失效
		if (StringUtils.isBlank(appPath)) {
			appPath = "";
		}

		if (null == appBase) {
			if( 80 != request.getServerPort()){
				appBase = new StringBuffer(request.getScheme()).append("://")
						.append(request.getServerName()).append(":")
						.append(request.getServerPort()).append(appPath).toString();
			}else{
				appBase = new StringBuffer(request.getScheme()).append("://")
						.append(request.getServerName()).append(appPath).toString();
			}
		}

		// fixed for web app deploy to root server context ; at 2011-04-08 by
		// zhadiw
		// 如果应用部署的站点根目录，则 path 值为空，导致部分URL跳转失效
//		if (StringUtils.isBlank(appPath)) {
//			appPath = appBase;
//		}

		request.setAttribute("commonAppPath", appPath);
		request.setAttribute("commonAppBase", appBase);

//		log.info(sessId + " commonAppPath: " + appPath);
//		log.info(sessId + " commonAppBase: " + appBase);

	}

	@Override
	public String getReqPrefix() {

		return AppHelper.REQ_PREFIX;
	}

}
